import Taro, { Component } from '@tarojs/taro'
import { View, Picker } from '@tarojs/components'
import { AtForm, AtInput, AtIcon, AtSwitch, AtButton } from 'taro-ui'
import { Header } from '../common/header'
import QQMapWX from '../../utils/qqmap-wx-jssdk.min'
import '../common/header.scss'
import './add.scss'
import { connect } from '@tarojs/redux'
import { State, Props } from './index.interface'

@connect(({ address }) => ({
  ...address,
}))

export default class Add extends Component<State, Props> {
  state = {
    qqmapsdk: new QQMapWX({
      key: 'UI2BZ-ACGWD-5B244-HYLE4-MKLE5-2RBJY'
    }),
    sug: [],

    id: 0,
    consignee: '',
    contact: '',
    province: '',
    city: '',
    district: '',
    address: '',
    longitude: '',
    latitude: '',
    default: false,

    loading: false,

    searchAddress: true
  }
  constructor(props: Props) {
    super(props);
  }
  componentDidMount() {

  }

  onClickLeftIcon() {
    Taro.navigateTo({
      url: '/pages/index/index'
    });
  }

  handleChange(field, value) {
    if (field === 'consignee') {
      this.setState({
        consignee: value,
      })
    }
    if (field === 'contact') {
      this.setState({
        contact: value,
      })
    }
    if (field === 'address') {
      this.setState({
        address: value.detail.value,
      })
    }

    if (field === 'default') {
      this.setState({
        default: !this.state.default,
      })
    }
  }

  handleDistrictChange(e) {
    let province = this.state.province[e.detail.value[0] ? e.detail.value[0] : 0]
    let city = this.state.city[e.detail.value[1] ? e.detail.value[1] : 0]
    let district = this.state.district[e.detail.value[2] ? e.detail.value[2] : 0]
    this.setState({
      selectProvince: province,
      selectCity: city,
      selectDistrict: district,
    });
  }

  onColumnchange(e) {
    let that = this;
    let user = Taro.getStorageSync('user');

    let parent_id = 0;
    let level = 'province';
    if (e.detail.column === 0) {
      parent_id = this.state.province[e.detail.value].id;
      level = 'city';
    }
    if (e.detail.column === 1) {
      parent_id = this.state.city[e.detail.value].id;
      level = 'district';
    }
    if (parent_id > 0) {
      Taro.request({
        credentials: 'include',
        url: 'https://guoxiaojian.guoxiaoge.cn/api/tool/district',
        data: {
          parent_id: parent_id,
          token: user.token,
          level: level
        },
        success: (res) => {
          if (res.statusCode === 200) {
            if (res.data.status === 'SUCCESS') {
              let selectorC = [];
              let selectorD = [];
              let selector = this.state.selector;
              for (let i = 0; i < res.data.data.city.length; i++) {
                selectorC.push(res.data.data.city[i].name);
              }
              for (let i = 0; i < res.data.data.district.length; i++) {
                selectorD.push(res.data.data.district[i].name);
              }
              if (e.detail.column == 0) {
                selector[1] = selectorC;
                selector[2] = selectorD;
                that.setState({
                  city: res.data.data.city,
                  district: res.data.data.district,
                  selector: selector
                });
              } else {
                selector[2] = selectorD;
                that.setState({
                  district: res.data.data.district,
                  selector: selector
                });
              }
            } else {
              if (res.data.status === 'FAILED') {
                if (res.data.failedCode === 'NO_LOGIN') {
                  Taro.navigateTo({
                    url: '/pages/login/login'
                  });
                }
              }
            }
          }
        }
      })
    }
  }


  handleSubmit() {
  }

  handleFocus() {
    Taro.navigateTo({
      url: '/pages/address/search'
    });
  }

  async handleSelect(item) {
    const { dispatch } = this.props;
    await dispatch({
      type: 'address/setSug',
      payload: { sug: item }
    })

    this.setState({
      ...this.state,
      address: item.title,
      longitude: item.latitude,
      latitude: item.longitude,
      searchAddress: false,
      sug: [],
    });
  }
  handleAddressChange(value) {
    let __this = this;
    if(value.length === 0){
      this.setState({
        searchAddress: true
      });
    }
    if (this.state.searchAddress && value.length!=0) {
      this.state.qqmapsdk.getSuggestion({
        //获取输入框值并设置keyword参数
        keyword: value, //用户输入的关键词，可设置固定值,如keyword:'KFC'
        region: '长沙', //设置城市名，限制关键词所示的地域范围，非必填参数
        success: async function (res) {//搜索成功后的回调
          var sug = [];
          for (var i = 0; i < res.data.length; i++) {
            sug.push({
              title: res.data[i].title,
              id: res.data[i].id,
              addr: res.data[i].address,
              city: res.data[i].city,
              district: res.data[i].district,
              latitude: res.data[i].location.lat,
              longitude: res.data[i].location.lng
            });
          }
          __this.setState({
            sug
          });
        },
        fail: function (error) {
          console.error(error);
        },
        complete: function (res) {
          console.log(res);
        }
      });
    }
  }

  handleUpdateSubmit() {

  }

  render() {
    const { sug } = this.props;
    return (
      <View>
        <Header
          leftIconType='chevron-left'
          onClickLeftIcon={this.onClickLeftIcon}
          title={this.state.id ? '修改收货地址' : '添加收货地址'}>
        </Header>
        <View>
          <AtForm>
            <AtInput
              name='name'
              title='收货人'
              type='text'
              border={true}
              value={this.state.consignee}
              onChange={this.handleChange.bind(this, 'consignee')}
            />
            <AtInput
              name='mobile'
              title='联系电话'
              type='phone'
              border={true}
              value={this.state.contact}
              onChange={this.handleChange.bind(this, 'contact')}
            />
            <View style={{ 'marginLeft': '15px', 'borderBottom':'1px solid #f5f5f5' }}>
              <Picker mode='multiSelector' value={'0'} range={this.state.selector} onChange={this.handleDistrictChange} onColumnchange={this.onColumnchange}>
                <View className='picker-view'>
                  <View className='picker-view-title'>所在地区</View>
                  <View className='picker-view-notice'>
                    <View>
                      {
                        this.state.selectProvince
                          ?
                          this.state.selectProvince.name
                          :
                          ""
                      }
                      {
                        this.state.selectCity
                          ?
                          this.state.selectCity.name
                          : ""
                      }
                      {
                        this.state.selectDistrict
                          ?
                          this.state.selectDistrict.name
                          : ""
                      }
                    </View>

                    <View>
                      <AtIcon value='chevron-right' size='22' color='#B1B1B1'></AtIcon>
                    </View>
                  </View>
                </View>
              </Picker>
            </View>
            <AtInput
              name='address'
              value={this.state.address}
              border={true}
              onChange={this.handleAddressChange.bind(this)}
              placeholder='请填写详细地址'
            />
            <View className="search-address">
              {
                this.state.sug.map(function (item) {
                  return <View onClick={this.handleSelect.bind(this, item)}>{item.title}</View>
                })
              }
            </View>
            <AtSwitch title='设为默认' color="#F2CA26" checked={this.state.default} onChange={this.handleChange.bind(this, 'default')} />
          </AtForm>

          <View className='address-submit'>
            {
              this.state.id
                ?
                <AtButton loading={this.state.loading} onClick={this.handleUpdateSubmit} type='primary'>修改</AtButton>
                :
                <AtButton loading={this.state.loading} onClick={this.handleSubmit} type='primary'>保存</AtButton>
            }
          </View>
        </View>
      </View>
    )
  }
}